import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
// 控制用户权限的地方
import router from '@/router'
import store from '@/store'
import getPageTitle from './utils/get-page-title'
// 1.添加路由前置守卫  2.设置白名单
const whilteList = ['/login', '/404']
router.beforeEach(async(to, from, next) => {
  // 进度条开始
  NProgress.start()
  const token = store.state.user.token
  // 先判断用户是否有token
  if (token) {
    // 判断有无用户id
    if (!store.getters.userId) {
      // 获取用户信息
      await store.dispatch('user/getuserinfo')
    }
    // 判断是否去登录页
    if (to.path === '/login') {
      next('/')
      NProgress.done()
    } else {
      next()
    }
  } else {
    // includes 判断数组中元素是否包含
    if (whilteList.includes(to.path)) {
      next()
    } else {
      // 没有token,去的也不是白名单内，强行去登录页
      next('/login')
      NProgress.done()
    }
  }
})
// 处理标题的前置守卫
router.beforeEach((to, from, next) => {
  document.title = getPageTitle(to.meta.title)
  next()
})
// 后置守卫
router.afterEach(() => {
  NProgress.done()
})
